﻿using AutoMapper;
using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.API.Write.Application.Command.PhysicalGrid;
using SC.GridManage.Domain.Models;

namespace SC.GridManage.API.Write.Application.Handler.PhysicalGrid
{
    public class UpdatePhysicalGridHandler : IRequestHandler<UpdatePhysicalGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PhysicalGridModel> physicalGridRepo;
        private readonly ILogger<CreatePhysicalHandler> logger;
        private readonly IMapper mapper;

        public UpdatePhysicalGridHandler(IBaseRepository<PhysicalGridModel> physicalGridRepo,
            ILogger<CreatePhysicalHandler> logger,
            IMapper mapper)
        {
            this.physicalGridRepo = physicalGridRepo;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 中介者组件 - 更新物理网格的处理方法
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(UpdatePhysicalGridCommand request, CancellationToken cancellationToken)
        {

            //定义一个ApiResult  公共响应类
            ApiResult<int> result = new ApiResult<int>();


            //判断数据库里是否已经存在这个网格编号了
            if(physicalGridRepo.QueryAsync().Result.Where(x => x.GridNo == request.GridNo & x.Id != request.Id).Any()){
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
                result.Msg = "网格编号已存在.";
                //把result 返回给控制器(调用方)
                return Task.FromResult(result);
            }

            var model = mapper.Map<PhysicalGridModel>(request); 
            int r=  physicalGridRepo.UpdateAsync(model).Result;


            if (r > 0)//判断受影响的行数是否大于0
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Success;
                result.Msg = "更新成功.";
                result.Data = r;
            }
            else
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
                result.Msg = "更新失败.";
            }
            //把 公共响应类result 返回给控制器(调用方)
            return Task.FromResult(result); 
        }
    }
}
